package com.yuye.cloud.common.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.yuye.cloud.common.constant.SecurityConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 租户holder
 *
 * @author xgf
 */
public class TenantContextHolder {
    /**
     * 支持父子线程之间的数据传递
     */
    private static final ThreadLocal<String> CONTEXT = new TransmittableThreadLocal<>();

    public static void setTenant(String tenant) {
        CONTEXT.set(tenant);
    }

    public static String getTenant() {
    	String tenant = CONTEXT.get();
    	if(StringUtils.isBlank(tenant)) {
    		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            tenant = request.getHeader(SecurityConstants.TENANT_HEADER);
    	}
    	
        return tenant;
    }

    public static void clear() {
        CONTEXT.remove();
    }
}
